<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>考试列表</title>
    <link rel="stylesheet" href="/static/web/css/style.css?v=<?= time() ?>">
    <script src="/static/component/jquery_3.3.1.js"></script>
</head>
<body class="container">
<div class="wrapper">
    <main>
        <h2>📋 可参加考试</h2>
        <div class="exam-list" id="exam-list" style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px;"></div>
        <div class="pagination" id="pagination"></div>
    </main>
</div>

<script src="/static/web/js/layout.js?v=" + Date.now() ></script>
<script src="/static/web/js/checklogin.js?v=" + Date.now() ></script>


<script>

    $(function () {

        let exams = [];
        const itemsPerPage = 2;
        let currentPage = 1;

        // 获取考试数据（从/web.Exam/list接口）
        $.ajax({
            url: "/web.Exam/list",
            method: "POST",
            dataType: "json",
            success: function (response) {
                if (response.code === 10401) {
                    window.location.href = '/web/login.html';
                }
                if (response.code === 0 && Array.isArray(response.data.data)) {
                    exams = response.data.data;
                    renderExams(currentPage);
                    renderPagination(Math.ceil(response.data.total / itemsPerPage));
                } else {
                    console.error("[ERROR] 接口返回数据格式不正确:", response);
                }
            },
            error: function (xhr, status, error) {
                alert("无法加载考试数据，请稍后重试！");
            }
        });

        // 渲染考试列表
        function renderExams(page) {
            const startIndex = (page - 1) * itemsPerPage;
            const endIndex = page * itemsPerPage;
            const paginatedExams = exams.slice(startIndex, endIndex);

            $("#exam-list").empty();
            paginatedExams.forEach(exam => {
                $("#exam-list").append(`
          <div class="card">
            <h3>${exam.name}</h3>
            <p><strong>科目：</strong>${exam.name}</p>
            <p><strong style="color: red">注意事项：</strong>${exam.description} 题</p>
            <p><strong>时长：</strong>${exam.duration} 分钟</p>
            <p><strong>允许考试组织：</strong>${exam.allow_orgs}</p>
            <p><strong>开考日期：</strong>${exam.start_time}</p>
            <a href="exam.html?paperId=${exam.paper_id}&examId=${exam.id}" class="btn" id="exam-btn-${exam.id}">立即参加考试</a>
          </div>
        `);
                // 获取并设置按钮状态
                setExamButtonStatus(exam.id);
            });
        }

        // 设置考试按钮状态
        function setExamButtonStatus(examId) {
            $.ajax({
                url: "/web.Exam/setExamBtnStatus",
                method: "POST",
                data: { exam_id: examId },
                dataType: "json",
                success: function (response) {
                    console.log("[DEBUG] 获取考试按钮状态成功:", response);
                    if (response.code === 0) {
                        const btn = $(`#exam-btn-${examId}`);
                        if (response.data.use_exam == 0) {
                            btn.addClass('disabled');
                            btn.attr('href', 'javascript:void(0)');
                            btn.css('cursor', 'not-allowed');
                            btn.css('opacity', '0.5');
                        } else {
                            btn.removeClass('disabled');
                            btn.css('cursor', 'pointer');
                            btn.css('opacity', '1');
                        }
                    }
                },
                error: function (xhr, status, error) {
                    console.error("无法获取考试按钮状态:", error);
                }
            });
        }

        // 渲染分页控件
        function renderPagination(totalPages) {
            $("#pagination").empty();

            for (let i = 1; i <= totalPages; i++) {
                $("#pagination").append(`<button class="blue-pagination">${i}</button>`);
            }

            $(".blue-pagination").on("click", function () {
                currentPage = parseInt($(this).text());
                renderExams(currentPage);
            });
        }
    });
</script>
</body>
</html>